let Cesium;

let handler = null;
let drawingMode = '';
let nttCollection = {
    pointsArr:[],//存储单击的坐标
    pointNtts:[],//存储点实体
    lineNtts:[],//存储线实体
    polgNtts:[],//存储面实体
    billbordNtt:[],//存储广告牌实体
  };
let toolTip;
let viewer;


const measureUtil = {
  //在init的时候，传入
  draw(drawMode,drawViewer,drawCesium){
    Cesium = drawCesium;
    viewer = drawViewer;
    this.clearDraw()

    drawingMode = drawMode;

    toolTip = document.createElement("div");
    toolTip.style.zIndex = 1000;
    toolTip.style.display = "none";
    toolTip.style.position = "absolute";
    toolTip.style.height = "20px";
    toolTip.style.width = "164px";
    toolTip.style.backgroundColor = "olive";
    toolTip.style.fontSize = "8px";

    let tooltipFlag = true;

    handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);

    //添加鼠标左键单击事件
    handler.setInputAction( (event) => {
      let earthPosition = viewer.camera.pickEllipsoid(event.position);
      if (Cesium.defined(earthPosition)) {
        nttCollection.pointsArr.push(earthPosition);//添加坐标点
        if(nttCollection.pointsArr.length > 1 && drawingMode === 'line'){
          nttCollection.lineNtts.push(this.createLine(nttCollection.pointsArr));
        }
        if(nttCollection.pointsArr.length > 2 && drawingMode === 'polygon'){
          nttCollection.polgNtts.push(this.createPolygon(nttCollection.pointsArr));
          if(nttCollection.polgNtts.length > 1){
            viewer.entities.remove(nttCollection.polgNtts[0]); //从场景中移除上个图形
            nttCollection.polgNtts.shift(); //从数组中移除上个图形
          }
        }
        nttCollection.pointNtts.push(this.createPoint(earthPosition,nttCollection,drawingMode));//添加新创建的点实体
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    //鼠标移动
    handler.setInputAction((event) => {
      this.setTooltip(event,tooltipFlag)
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    //鼠标右键
    handler.setInputAction( () => {
      if(drawingMode === 'line'){
        if(nttCollection.pointsArr.length > 1){
          nttCollection.billbordNtt.push(this.createBillboard(nttCollection.pointsArr));
          nttCollection.pointsArr = [];
          this.resetHandler();
          toolTip.style.display = "none";
          tooltipFlag = false;
        }else {
          alert('请选择2个以上的点再执行右键结束命令');
        }
      }else if(drawingMode === 'polygon'){
        if(nttCollection.pointsArr.length > 2){
          nttCollection.billbordNtt.push(this.createBillboard(nttCollection.pointsArr));
          nttCollection.billbordNtt.push(this.createAreaLable(nttCollection.pointsArr));
          nttCollection.pointsArr = [];
          this.resetHandler();
          toolTip.style.display = "none";
          tooltipFlag = false;
        }else {
          alert('请选择3个以上的点再执行右键结束命令');
        }
      }

    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

  },



  //tooltip跟随
  setTooltip(event,tooltipFlag){
    if(tooltipFlag){
      toolTip.style.left = event.endPosition.x + 40 + "px";
      toolTip.style.top = event.endPosition.y + 0 + "px";
      toolTip.innerHTML = '单击选择节点，右键结束量测';
      toolTip.style.display = "block";
    }
  },

  //重置handler：关闭量测时候的事件，增加点击清除的事件
  resetHandler(){
    if (handler != null) {
      handler.destroy();
    }
    handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
    handler.setInputAction( (event) => {
      let pick = viewer.scene.pick(event.position);
      if (Cesium.defined(pick) && (pick.id.id === 'delBillboard')) {
        this.clearDraw();
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
  },

  //清除绘制痕迹
  clearDraw(){
    if (handler != null) {
      handler.destroy();
      handler = null;
    }

    nttCollection.pointNtts.forEach((item)=>{
      viewer.entities.remove(item);
    });
    nttCollection.lineNtts.forEach((item)=>{
      viewer.entities.remove(item);
    });
    nttCollection.polgNtts.forEach((item)=>{
      viewer.entities.remove(item);
    });
    nttCollection.billbordNtt.forEach((item)=>{
      viewer.entities.remove(item);
    });

    drawingMode = '';
    nttCollection = {
      pointsArr:[],
      pointNtts:[],
      lineNtts:[],
      polgNtts:[],
      billbordNtt:[],
    };
  },

  //创建显示面积的lable
  createAreaLable(pointsArr){
    let area = this.getPolygonArea(pointsArr);
    let areaLable = viewer.entities.add({
      position: pointsArr[pointsArr.length-1],
      label: {
        text: area + '㎡',
        font: '18px sans-serif',
        fillColor: Cesium.Color.GOLD,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        outlineWidth: 2,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        pixelOffset: new Cesium.Cartesian2(20, -20),
      }
    });
    return areaLable;
  },
  //创建清除按钮，即delBillboard
  createBillboard(pointsArr){
    return viewer.entities.add({
      id: 'delBillboard',
      position: pointsArr[pointsArr.length - 1],
      billboard: {
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        image: "../../static/image/del.svg",
        scaleByDistance: new Cesium.NearFarScalar(1.5e2, 1.5, 8.0e6, 0.0),
        horizontalOrigin: Cesium.HorizontalOrigin.LEFT
      },
    });

  },
  //创建面
  createPolygon(pointsArr){
    return viewer.entities.add({
      polygon: {
        hierarchy: new Cesium.PolygonHierarchy(pointsArr),
        material: new Cesium.ColorMaterialProperty(Cesium.Color.WHITE.withAlpha(0.7)),
        height: 0.1
      }
    });
  },
  //创建线
  createLine(pointsArr){
    return viewer.entities.add({
      polyline: {
        positions: [pointsArr[pointsArr.length - 2], pointsArr[pointsArr.length - 1]],
        show: true,
        material: Cesium.Color.RED,
        width: 2,
        clampToGround: true,
      }
    });
  },
  //创建点
  createPoint(earthPosition,nttCollection,drawingMode){
    let tempPosition;
    if (nttCollection.pointNtts.length > 0 && drawingMode === 'line'){
      let distance = this.getSpaceDistance(nttCollection.pointsArr);
      tempPosition = viewer.entities.add({
        position: earthPosition,
        point: {
          pixelSize: 5,
          color: Cesium.Color.RED,
          outlineColor: Cesium.Color.WHITE,
          outlineWidth: 2,
        },
        label: {
          text: distance + 'm',
          font: '18px sans-serif',
          fillColor: Cesium.Color.GOLD,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          outlineWidth: 2,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          pixelOffset: new Cesium.Cartesian2(20, -20),
        }
      });
    }else{
      tempPosition = viewer.entities.add({
        position: earthPosition,
        point: {
          pixelSize: 5,
          color: Cesium.Color.RED,
          outlineColor: Cesium.Color.WHITE,
          outlineWidth: 2,
        }
      });
    }
    return tempPosition;//添加新创建的点实体
  },
  //计算长度
  getSpaceDistance(positions) {
    let distance = 0;
    for (let i = 0; i < positions.length - 1; i++) {

      let point1cartographic = Cesium.Cartographic.fromCartesian(positions[i]);
      let point2cartographic = Cesium.Cartographic.fromCartesian(positions[i+1]);
      /**根据经纬度计算出距离**/
      let geodesic = new Cesium.EllipsoidGeodesic();
      geodesic.setEndPoints(point1cartographic, point2cartographic);
      let s = geodesic.surfaceDistance;
      //console.log(Math.sqrt(Math.pow(distance, 2) + Math.pow(endheight, 2)));
      //返回两点之间的距离
      s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2));
      distance = distance + s;
    }
    return distance.toFixed(2);
  },
  //计算面积
  getPolygonArea(point) {//输入应该是经纬度
    let points = [];
    point.forEach((item) =>{
      let cartographic = Cesium.Cartographic.fromCartesian(item);
      let longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
      let latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
      points.push({ lon: longitudeString, lat: latitudeString });
    });

    let earthRadiusMeters = 6371000.0;
    let radiansPerDegree = Math.PI / 180.0;

    let totalAngle = 0;
    for (let i = 0; i < points.length; i++) {
      let j = (i + 1) % points.length;
      let k = (i + 2) % points.length;
      totalAngle += this.Angle(points[i], points[j], points[k]);
    }
    let planarTotalAngle = (points.length - 2) * 180.0;
    let sphericalExcess = totalAngle - planarTotalAngle;
    if (sphericalExcess > 420.0) {
      totalAngle = points.length * 360.0 - totalAngle;
      sphericalExcess = totalAngle - planarTotalAngle;
    } else if (sphericalExcess > 300.0 && sphericalExcess < 420.0) {
      sphericalExcess = Math.abs(360.0 - sphericalExcess);
    }
    return (sphericalExcess * radiansPerDegree * earthRadiusMeters * earthRadiusMeters).toFixed(2);
  },
  /**
   * @return {number}
   */
  Angle(p1, p2, p3) {
    let bearing21 = this.Bearing(p2, p1);
    let bearing23 = this.Bearing(p2, p3);
    let angle = bearing21 - bearing23;
    if (angle < 0) {
      angle += 360;
    }
    return angle;
  },
  /**
   * @return {number}
   */
  Bearing(from, to) {
    let degreesPerRadian = 180.0 / Math.PI;
    let radiansPerDegree = Math.PI / 180.0;
    let lat1 = from.lat * radiansPerDegree;
    let lon1 = from.lon * radiansPerDegree;
    let lat2 = to.lat * radiansPerDegree;
    let lon2 = to.lon * radiansPerDegree;
    let angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2));
    if (angle < 0) {
      angle += Math.PI * 2.0;
    }
    angle = angle * degreesPerRadian;
    return angle;
  },

};
export default measureUtil
